<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <div class="leftbox">
      <!-- 树节点过滤 -->
      <div>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          v-model="filterText"
        >
        </el-input>
      </div>
      <!-- 树组件 -->
      <div style="margin-top: 15px;height: 95%;overflow: hidden;
        overflow-y: auto;">
        <el-tree
          ref="tree"
          :props="props"
          :highlight-current="true"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode"
          :load="loadNode"
          lazy>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="bodybox">
      <!-- 新增按钮 -->
      <div class="top">
        <button class="buttom" @click="submit('zen')">
          <i class="el-icon-plus" style="font-size: 12px; color: #fff"></i>新增
        </button>
      </div>
      <!-- 循环图片盒子 -->
      <div class="imgbox">
        <el-empty v-show="entity.length==0" :image-size="300" style="margin-left: 40%;"></el-empty>
        <div class="littlebox" v-for="(item, index) in entity" :key="index">
          <div>{{ item.createUser }}</div>
          <div>
            <img
              class="img"
              :src="'data:image:gif;base64,' + item.logoImage"
              alt=""
            />
          </div>
          <div>
            <el-button type="text" style="color: red" @click="del(item)"
              >删除</el-button
            >
            <el-button type="text" @click="submit(item)">编辑</el-button>
          </div>
        </div>
      </div>
      <!-- 新增/修改弹框 -->
      <div>
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          :center="true"
        >
          <div class="dialog">
            <div class="title">
              {{ isbianji == "zen" ? "新增" : "编辑" }}企业logo信息
            </div>
            <!-- 企业下拉 -->
            <div class="xiala">
              <span>企业名称 </span>
              <span>
                <el-select v-model="value" placeholder="请选择" size="mini">
                  <el-option
                    v-for="(item, index) in options"
                    :key="index"
                    :label="item.bizOrgName"
                    :value="item.bizOrgNo"
                  >
                  </el-option>
                </el-select>
              </span>
            </div>
            <div class="updata">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :http-request="httpRequest"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <span v-if="imageUrl">
                  <img :src="imageUrl" class="avatar" />
                </span>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="text">注意：请上传140*45像素图片文件，格式为png;</div>
          </div>
          <div style="margin-top: 10px; text-align: center">
            <button
              @click="quxiao"
              style="
                width: 60px;
                height: 30px;
                margin-right: 10px;
                background-color: #fff;
                border: 1px solid #ccc;
              "
            >
              取 消
            </button>
            <button
              @click="sure"
              style="
                width: 60px;
                height: 30px;
                background-color: #3b8eea;
                color: #fff;
                border: none;
              "
            >
              确 定
            </button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getuserlogoapi,
  postuserlogoapi,
  deluserlogoapi,
  putuserlogoapi
} from '@/api/logo'
import { gettreelist, gettreexiaji } from '../../api/userscreen'
import { getloginuserapi, getyonghuxialaapi } from '@/api/cycle'
export default {
  name: 'CallPoliceIndex',
  data () {
    return {
      value: '',
      imageUrl: '',
      entity: [],
      options: [],
      filterText: '',
      props: {
        label: 'bizOrgName',
        disabled: 'disabled'
      },
      dialogVisible: false,
      fileBase64: '',
      isbianji: ''
    }
  },
  async mounted () {},

  methods: {
    // 新增/修改
    submit (val) {
      this.isbianji = val
      if (this.options.length == 0) {
        this.$message.warning('请先选择企业')
      } else {
        this.dialogVisible = true
        console.log(val)
        if (val !== 'zen') {
          this.imageUrl = 'data:image:gif;base64,' + val.logoImage
        } else {
          this.imageUrl = ''
        }
      }
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      // this.getBase64(file.raw).then((res) => {
      //   this.imageUrl = res;
      //     console.log(res);
      //     //ruleForm是我接收后端传过来的数据，此处可以忽略
      //     this.ruleForm.imagePath = res;
      //   });
    },
    // 图片上传之后的回调
    beforeAvatarUpload (file) {
      console.log(file)
    },
    httpRequest(data) {
      this.imageUrl = URL.createObjectURL(data.file)
      // 这是限制上传文件类型
      const isPFX =
        data.file.type === 'image/jpeg' ||
        data.file.type === 'image/jpg' ||
        data.file.type === 'image/png'
      const isLt2M = data.file.size / 1024 / 1024 < 2
      if (!isPFX) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG 格式!')
      } else if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      } else {
        this.getBase64(data.file).then((resBase64) => {
          this.fileBase64 = resBase64.split(',')[1] // 直接拿到base64信息
          console.log(this.fileBase64)
        })
      }
    },
    // 这个file参数 也就是文件信息，你使用 插件 时 你就可以打印出文件信息 看看嘛
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        let fileResult = ''
        reader.readAsDataURL(file)
        // 开始转
        reader.onload = function () {
          fileResult = reader.result
        }
        // 转 失败
        reader.onerror = function (error) {
          reject(error)
        }
        // 转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult)
        }
      })
    },
    //  取消/弹框关闭
    quxiao () {
      this.dialogVisible = false
      this.imageUrl = ''
      this.isshow = false
    },
    // 确认修改并保存
    async sure () {
      this.isbianji == 'zen'
        ? await postuserlogoapi({
          owner: this.value,
          logoImage: this.fileBase64,
          createUser: 'XTYS2024'
        })
        : await putuserlogoapi({
          owner: this.value,
          logoImage: this.fileBase64
        })
      this.dialogVisible = false
      const res = await getuserlogoapi({ owner: this.value })
      if (res.code == 200) {
        this.entity = [res.data.entity]
      } else {
        this.entity = []
      }
    },
    // 删除头像
    del (item) {
      console.log(item)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deluserlogoapi({ owner: item.owner })
          this.$message.success('删除成功')
          const res = await getuserlogoapi({ owner: this.value })
          if (res.code == 200) {
            this.entity = [res.data.entity]
          } else {
            this.entity = []
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 树节点点击
    async handleNodeClick (val) {
      this.options = [val]
      this.value = val.orgNo
      console.log(val);
      const res = await getuserlogoapi({ owner: val.bizOrgNo })
      console.log(res);
      if (res.code == 200) {
        this.entity = [res.data.entity]
        console.log( this.entity);
      } else {
        this.entity = []
      }
    },
    // 树组件懒加载
    async loadNode (node, resolve) {
      const re = await getloginuserapi()
      if (re.data.entity.orgType !== '04') {
        const res = await gettreelist()
        console.log(res);
        if (node.level === 0) {
          // 初始的级数（最顶层）
          return resolve(res.data.list) // 最顶层数据渲染为region
        }
        const ress = await gettreexiaji({ orgNo: node.data.bizOrgNo })
        if (node.level === 1) {
          return resolve(ress.data.list)
        } else if (node.level === 2) {
          return resolve([])
        }
      } else {
        if (node.level === 0) {
          const res = await getyonghuxialaapi()
          return resolve(res.data.list)
        } else {
          return resolve([])
        }
      }
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.bizOrgName.indexOf(value) !== -1
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.bigbox {
  background-color: #f1f1f1;
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox {
    width: 300px;
    height: 100%;
    background-color: #fff;
    padding: 20px;
  }
  .bodybox {
    flex: 1;
    margin-left: 10px;
    background-color: #fff;
    height: 100%;
    padding: 20px;
    .top {
      text-align: right;
      .buttom {
        width: 70px;
        height: 30px;
        background-color: #1890ff;
        color: #fff;
        border-radius: 3px;
        border: none;
      }
    }
    .imgbox {
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;

      .littlebox {
        margin-right: 10px;
        margin-bottom: 20px;
        width: 24%;
        height: 180px;
        border: 1px solid #ccc;
        border-radius: 3px;
        padding: 10px;
        .img {
          height: 100px;
          width: 100%;
        }
      }
    }
    .dialog {
      .title {
        font-size: 18px;
        margin-bottom: 30px;
      }
      .xiala {
        margin-bottom: 30px;
      }
      .updata {
        margin-bottom: 20px;
        width: 177px;
        height: 100px;
        // border: 1px solid #ccc;
      }
      .text {
        font-size: 12px;
        color: #3b8eea;
      }
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 268px;
  height: 100px;
  display: block;
}
::v-deep .el-dialog__header {
  display: none;
}
::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #bae7ff !important;
}
::v-deep .el-tree-node__content{
  &:hover{
    background-color: #f0f7ff;
  }
}
</style>
